<?php

namespace app\company\controller\consult\subset;

use app\BaseController;
use app\model\ConsultTimeModel;
use app\model\UnitModel;
use think\App;

class Scheduling extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }


    /**
     * 每月每月排班视图
     * @return bool|string
     */
    public function Index(): bool|string
    {
        try {
            $param = $this->request->param();//Y-m
            $this->validate($param, [
                'date|时间' => 'require',
                'unit_id|单位ID' => 'require'
            ]);
            $date_time = strtotime($param['date'] . '-01');
            $t = date('t', $date_time);
            $start_time = date('Ym01', $date_time);
            $end_time = date('Ym' . $t, $date_time);
            $where = [];
            $where[] = ['unit_id','=',$param['unit_id']];
            $where[] = ['date', 'between', [$start_time, $end_time]];
            $ConsultTimeModel = new ConsultTimeModel();
            $list = $ConsultTimeModel->where($where)->with([
                'consult'
            ])->select()->toArray();
            $data = [];
            foreach ($list as $item) {
                $data[$item['date']][$item['consult_id']][] = $item;
            }
            $data2 = [];
            foreach ($data as $key => $item) {
                $users = [];
                foreach ($item as $items) {
                    $nickname = '';
                    $appointment = [];
                    foreach ($items as $v) {
                        $nickname = $v['consult_name'];
                        $appointment[] = [
                            'start' => date('H:i', $v['start_time']),
                            'end' => date('H:i', $v['end_time']),
                            'is_reservation' => $v['is_reservation'],
                        ];
                    }
                    $users[] = [
                        'nickname' => $nickname,
                        'appointment' => $appointment,
                    ];
                }
                $data2[] = [
                    'date' => strtotime($key),
                    'users' => $users
                ];
            }
            $UnitModel = new UnitModel();
            return success([
                'data' => $data2,
                'unit_name' => $UnitModel->where('id','=',$param['unit_id'])->value('name')
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}